<template>
  <div class="detailsBox" v-show="displayStore().isShowRights">
    <!-- 顶部 -->
    <div class="topPart flex jc-space-between">
      <div class="textbg"></div>
    </div>
    <!-- 中间 -->
    <div class="centerPart">
      <!-- 卡片 -->
      <div class="card">
        <div class="cardTitle">{{ rightsInfo?.benefitName }}</div>
        <div class="imgBox">
          <img
            :src="
              rightsInfo?.benefitCover ? rightsInfo?.benefitCover : defaultIcon
            "
            alt="权益封图"
          />
        </div>
        <div class="timeGroup">
          <div class="time">获取时间：{{ rightsInfo?.payTimeStr }}</div>
          <div class="time">
            过期时间：{{ getEndTime(rightsInfo?.payTimeStr) }}
          </div>
        </div>
        <div class="state1" v-if="rightsInfo?.grantStatus == 2"></div>
        <div class="state2" v-if="rightsInfo?.grantStatus == 1"></div>
      </div>
      <!-- 规则内容 -->
      <div
        class="rulePart"
        :style="{
          height: `${
            rightsInfo?.benefitType == benefitType.directCharge
              ? 'calc(100% - 360px)'
              : 'calc(100% - 200px)'
          }`,
        }"
      >
        <div class="userText"></div>
        <iframe class="ruleContent" :src="htmlUrl" frameborder="0"></iframe>
      </div>
      <!-- 兑换码 -->
      <div
        class="codePart flex jc-center al-center flex-cloumn"
        v-if="rightsInfo?.benefitType == benefitType.exchangeCode"
        @click="toCopy"
      >
        <div class="codeBox">{{ rightsInfo?.exchangeCode }}</div>
        <div class="tip">请复制兑换码到权益方使用</div>
        <div class="copyBtn">复制兑换码</div>
      </div>
      <!-- 收获地址 -->
      <div
        class="addressPart flex jc-center al-center flex-cloumn"
        v-if="rightsInfo?.benefitType == benefitType.physicalReward"
      >
        <!-- <div class="addressPart flex jc-center al-center flex-cloumn"> -->
        <div
          class="openInput flex jc-center al-center flex-cloumn"
          v-if="!curAddressInfo.name"
        >
          <div class="addressBtn" @click="() => (isShowAddressInput = true)">
            填写收货人信息
          </div>
          <div class="tip">
            实物奖励一经发出，信息将无法更改，请务必仔细核对
          </div>
        </div>
        <!-- 展示收货信息 -->
        <div class="showInfo" v-if="curAddressInfo.name">
          <div>收货信息</div>
          <div class="updateBtn" @click="toUpdate">修改</div>
          <div>姓名：{{ curAddressInfo.name }}</div>
          <div>电话：{{ curAddressInfo.phone }}</div>
          <div>地区：{{ curAddressInfo.area }}</div>
          <div>地址：{{ curAddressInfo.address }}</div>
          <div>订单号:</div>
          <div>物流单号：</div>
          <div>配送物流：</div>
        </div>
        <!-- 录入收货信息 -->
        <div class="pop-mask" v-if="isShowAddressInput">
          <div class="container">
            <div class="confirm-layer">
              <div class="layer-title">
                {{ isUpdateAddress ? "修改地址" : "收货地址" }}
              </div>
              <div class="layer-message" style="padding: 250px 0 100px 0">
                <div class="flex jc-space-between">
                  <div class="title">姓名</div>
                  <input
                    class="box"
                    type="text"
                    v-model="addressInfo.name"
                    placeholder="收货人真实姓名"
                  />
                </div>
                <div class="flex jc-space-between">
                  <div class="title">电话</div>
                  <input
                    class="box"
                    type="text"
                    v-model="addressInfo.phone"
                    placeholder="收货人的联系电话"
                  />
                </div>
                <div class="flex jc-space-between">
                  <div class="title">地区</div>
                  <input
                    class="box"
                    type="text"
                    v-model="addressInfo.area"
                    placeholder="省、市、区、或直辖市"
                  />
                </div>
                <div class="flex jc-space-between">
                  <div class="title">地址</div>
                  <div class="textareaBox">
                    <textarea
                      v-model="addressInfo.address"
                      placeholder="填写详细的收货地址 例如：小区、街道、门牌号、房间号等"
                    ></textarea>
                  </div>
                </div>
                <div
                  class="flex al-center jc-center desc"
                  v-if="errerTip || isUpdateAddress"
                >
                  <div class="desc_icon"></div>
                  <span class="tip-text">{{
                    errerTip
                      ? errerTip
                      : "收货信息只能修改1次，请核对无误后再提交"
                  }}</span>
                </div>
              </div>
            </div>
            <div class="layer-btns">
              <div class="btn layer-cancel" @click="onCancel('info')">取消</div>
              <div class="btn layer-confirm" @click="onConfirm('info')">
                确定
              </div>
            </div>
          </div>
        </div>
        <!-- 再次确认 -->
        <div class="pop-mask" v-if="isShowConfirmTip">
          <div class="container">
            <div class="confirm-layer">
              <div class="layer-message" style="padding: 150px 0 100px 0">
                <div class="flex al-center jc-center desc">
                  <span class="tip-text"
                    >请确保信息填写准确无误，以免影响奖品配送</span
                  >
                </div>
              </div>
            </div>
            <div class="layer-btns">
              <div class="btn layer-cancel" @click="onCancel()">取消</div>
              <div class="btn layer-confirm" @click="onConfirm()">确定</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="bottomPart">
      <div class="split flex jc-space-between al-center">
        <div class="point3"></div>
        <div class="point2"></div>
        <div class="point1"></div>
        <div class="line"></div>
        <div class="point1"></div>
        <div class="point2"></div>
        <div class="point3"></div>
      </div>
      <div
        class="backBtn"
        @click="
          () => {
            displayStore().isShowRights = false;
          }
        "
      ></div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { getOrderBenefitByOrder } from "@/api/moudules/rights";
import { baseDataStore, displayStore } from "@/stores";
import { getCurrentInstance, onMounted, ref, watch } from "vue";
const cInstance = getCurrentInstance()?.appContext.config.globalProperties;
import defaultIcon from "../../assets/images/rights/icon.png";

enum benefitType {
  directCharge = "directCharge", // 直充到账
  physicalReward = "physicalReward", // 实物奖励
  exchangeCode = "exchangeCode", // 兑换码
}

type rightsInfoType = {
  id: number; //主键id
  orderNo: number; //订单编号
  benefitId: number; //权益id
  benefitType: string; //权益类型: directCharge（直充到账）、physicalReward（实物奖励）、exchangeCode（兑换码）
  benefitName: string; //权益名称
  benefitCover: string; //权益封面图片地址
  rightsDescription: string; //权益使用规则
  grantStatus: 1 | 2; //权益发放状态 1:未发放 2:已发放 默认为1
  grantTimeStr: string; //权益发放时间
  exchangeCode: string; //兑换码
  createTimeStr: string; //创建时间
  updateTimeStr: string; //修改时间
  sourceType: number; //来源类型 1:数藏市场订单 2:活动发行订单
  payTimeStr: string; //权益获取时间
  sourceTypeStr: string; //来源类型 1:数藏市场订单 2:活动发行订单
};

const htmlUrl = ref<string>("");
const rightsInfo = ref<rightsInfoType>();
const isShowAddressInput = ref<boolean>(false);
const isShowConfirmTip = ref<boolean>(false);
const isUpdateAddress = ref<boolean>(false);
const errerTip = ref<string>("");
const addressInfo = ref<any>({
  name: "",
  phone: "",
  area: "",
  address: "",
});
const curAddressInfo = ref<any>({
  name: "",
  phone: "",
  area: "",
  address: "",
  // name: "321",
  // phone: "13232123231",
  // area: "3211",
  // address: "123321"
});

const validationRules: any = {
  name: {
    required: true,
    minLength: 3,
    maxLength: 10,
  },
  phone: {
    required: true,
    phonePattern: /^1[3-9]\d{9}$/, //中国大陆校验
  },
  area: {
    required: true,
    // maxLength: 20
  },
  address: {
    required: true,
    // maxLength: 50
  },
};

const handleHtmlstr = (htmlContent: string) => {
  htmlContent = `<html>
<head>
<style>
  * {
    color: #fff; /* 设置所有文本颜色为白色 */
    font-size:14px;
    line-height:26px;
  }
</style>
</head>
<body>${htmlContent}</body>
</html>`;
  const blob = new Blob([htmlContent], { type: "text/html" });
  htmlUrl.value = URL.createObjectURL(blob);
};
const toCopy = () => {
  navigator.clipboard
    .writeText(`${rightsInfo.value?.exchangeCode}`)
    .then(() => {
      console.log("文本已复制到剪贴板");
      cInstance?.$Toast("复制成功");
    })
    .catch((err) => {
      console.error("复制文本到剪贴板失败:", err);
    });
};

const getRightsInfo = async (orderNo: number, benefitId: number) => {
  const orderInfo: any = await getOrderBenefitByOrder({ orderNo });
  const rightsInfoList: rightsInfoType[] =
    orderInfo.nftCollectionOrderBenefitInfo;
  const res = rightsInfoList.filter((item) => item.benefitId == benefitId)[0];
  if (res) {
    rightsInfo.value = res;
    handleHtmlstr(rightsInfo.value.rightsDescription);
  }
  console.log("rightsInfo.value", rightsInfo.value);

  // 权益详情假数据
  // rightsInfo.value = {
  //   id: 123,
  //   orderNo: 123,
  //   benefitId: 123,
  //   benefitType: "1",
  //   benefitName: "权益名称名称名称名称名称名称名称名称",
  //   benefitCover: "",
  //   rightsDescription: `<p>活动细则： 1、《头号玩家·Fre<span style=\"color: rgb(225, 60, 57);\">e City》用户</span><span style=\"color: rgb(225, 60, 57); background-color: rgb(235, 144, 58);\">专享</span><span style=\"background-color: rgb(235, 144, 58);\">福利活动</span>每月均可参与，每位用户限定领取一份（需当月现场领取，次月无效）； 2、【<strong>开心麻花购票立减券】在您购买藏品后24小时内发放至绑定的开心麻花</strong></p ><p><strong> &nbsp;尊敬的紫鲸藏友您好，您被福利砸中啦，获得开心</strong>麻花盲盒【“级别”N、R、SR、SSR、隐藏款】福利，购票门票抵用券兑换方式如下：微信小程序搜索【开心麻花】，购票时选择【<s>优惠券】，输入兑换码进</s>行兑换即可</p ><p> </p ><p> <img src=\"https://image.zijing.art/mspace/imagec8e13d7c-9aa3-4ca3-b57b-5b7096b6e153.jpg\" alt=\"培训证书.jpg\" data-href=\"https://image.zijing.art/mspace/imagec8e13d7c-9aa3-4ca3-b57b-5b7096b6e153.jpg\" style=\"width: 168.00px;height: 238.13px;\"/></p >`,
  //   grantStatus: 1,
  //   grantTimeStr: "",
  //   exchangeCode: "7C38QBV4Q2YW",
  //   createTimeStr: "",
  //   updateTimeStr: "",
  //   sourceType: 1,
  //   payTimeStr: "2024-02-02 12:12:12",
  //   sourceTypeStr: "1"
  // }
  // handleHtmlstr(rightsInfo.value.rightsDescription)
};

const getEndTime = (timestr: any) => {
  const time = new Date(timestr);
  const year = time.getFullYear() + 1;
  const month = time.getMonth() + 1;
  const day = time.getDate();
  const hours = time.getHours();
  const minutes = time.getMinutes();
  const seconds = time.getSeconds();
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const validateForm = () => {
  errerTip.value = "";
  for (const field in validationRules) {
    if (Object.prototype.hasOwnProperty.call(validationRules, field)) {
      const value = addressInfo.value[field].trim();
      console.log(validationRules[field], value);
      if (validationRules[field].required && !value) {
        errerTip.value = `${field} is required`;
        break;
      }

      if (
        validationRules[field].minLength &&
        value.length < validationRules[field].minLength
      ) {
        errerTip.value = `${field} must be at least ${validationRules[field].minLength} characters long.`;
        break;
      }

      if (
        validationRules[field].maxLength &&
        value.length > validationRules[field].maxLength
      ) {
        errerTip.value = `${field} must be no more than ${validationRules[field].maxLength} characters long.`;
        break;
      }

      if (
        validationRules[field].phonePattern &&
        !validationRules[field].phonePattern.test(value)
      ) {
        errerTip.value = `${field} is not a valid phone.`;
        break;
      }
    }
  }
  console.log(errerTip.value);
  if (errerTip.value) {
    return false;
  } else {
    return true;
  }
};

const onConfirm = (type?: string) => {
  if (type == "info") {
    if (validateForm()) {
      isShowConfirmTip.value = true;
    }
  } else {
    isShowAddressInput.value = false;
    isShowConfirmTip.value = false;
    curAddressInfo.value = addressInfo.value;
  }
};
const onCancel = (type?: string) => {
  if (type == "info") {
    isShowAddressInput.value = false;
    errerTip.value = "";
    addressInfo.value = {
      name: "321",
      phone: "13232123231",
      area: "3211",
      address: "123321",
    };
  } else {
    isShowConfirmTip.value = false;
  }
};

const toUpdate = () => {
  isUpdateAddress.value = true;
  isShowAddressInput.value = true;
  addressInfo.value = curAddressInfo.value;
};

onMounted(() => {
  getRightsInfo(+"6020079338786818", +"1034");
});

watch(
  () => baseDataStore().rightsInfo,
  (n: any) => {
    if (n) {
      console.log("rightsInfo", n);
      getRightsInfo(+n.orderNo, +n.benefitId);
    }
  }
);
</script>
<style lang="less" scoped>
.detailsBox {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 101;
  min-height: 100%;
  min-height: -webkit-fill-available;
  background: #b7a7ff;
  background: url("../../assets/images/rights/rightsbg.png");
  background-size: cover;
  background-repeat: no-repeat;

  .topPart {
    width: 100%;
    position: relative;

    .textbg {
      width: 347px;
      height: 109px;
      background: url("../../assets/images/aichat/titlebg.png");
      background-size: cover;
      position: absolute;
      top: 0;
      left: 0;

      &::after {
        content: "";
        width: 229px;
        height: 79px;
        background: url("../../assets/images/rights/title.png");
        background-size: cover;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
      }
    }
  }

  .bottomPart {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 3;

    &::after {
      position: absolute;
      content: "";
      top: 0;
      left: 0;
    }

    .backBtn {
      width: 183px;
      height: 95px;
      position: fixed;
      left: 0;
      bottom: 0;
      background: #fff;
      font-family: FZCuQian-M17S;
      font-weight: 400;
      background: url("../../assets/images/aichat/backBtn.png");
      background-size: cover;
    }

    .split {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 95px;
      width: 96%;
      margin: 15px 0;

      .line {
        width: 94%;
        height: 3px;
        background: #bcbae1;
      }

      .point1 {
        width: 4px;
        height: 3px;
        background: #bcbae1;
      }

      .point2 {
        width: 3px;
        height: 3px;
        background: #bcbae1;
        opacity: 0.8;
      }

      .point3 {
        width: 3px;
        height: 3px;
        background: #bcbae1;
        opacity: 0.5;
      }
    }
  }

  .centerPart {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    padding-top: 142px;

    .card {
      width: 100%;
      height: 248px;
      background: url("../../assets/images/rights/cardbg.png");
      background-size: contain;
      background-repeat: no-repeat;
      position: relative;

      .imgBox {
        width: 169px;
        height: 176px;
        background: url("../../assets/images/rights/iconbg.png");
        background-size: contain;
        background-repeat: no-repeat;
        position: absolute;
        left: 30px;
        bottom: 35px;

        // &::before {
        //   content: "";
        //   width: 110px;
        //   height: 199px;
        //   background: url("../../assets/images/rights/icon.png");
        //   background-size: contain;
        //   background-repeat: no-repeat;
        //   position: absolute;
        //   left: 50%;
        //   transform: translateX(-50%);
        //   top: 30px;
        // }

        img {
          width: 110px;
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          top: 30px;
        }
      }

      .time {
        font-family: FZCuYuan;
        font-weight: 400;
        font-size: 24px;
        color: #8f8ad3;
        line-height: 40px;
      }

      .timeGroup {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 65px;
      }

      .cardTitle {
        font-family: FZCuQian;
        font-weight: 400;
        font-size: 26px;
        color: #ffffff;
        line-height: 40px;
        font-style: italic;
        padding-top: 27px;
        margin-left: 200px;
        width: 400px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .state1 {
        background: url("../../assets/images/rights/fafang.png");
      }
      .state2 {
        background: url("../../assets/images/rights/nofafang.png");
      }
      .state1,
      .state2 {
        width: 134px;
        height: 117px;
        background-size: contain;
        background-repeat: no-repeat;
        position: absolute;
        right: 15px;
        bottom: 50px;
      }
    }

    .rulePart {
      width: 100%;
      height: calc(100% - 700px);
      padding: 30px 52px;

      .userText {
        width: 194px;
        height: 54px;
        background: url("../../assets/images/rights/usertext.png");
        background-size: cover;
        background-repeat: no-repeat;
        margin-bottom: 30px;
      }

      .ruleContent {
        width: 100%;
        height: calc(100% - 85px);
      }
    }

    .codePart {
      .codeBox {
        width: 95%;
        height: 126px;
        background: url("../../assets/images/rights/codebg.png");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        font-family: FZCuYuan;
        font-weight: 400;
        font-size: 36px;
        color: #ffffff;
        text-align: center;
        padding-top: 30px;
        letter-spacing: 3px;
        position: relative;

        &::after {
          content: "";
          width: 210px;
          height: 50px;
          background: url("../../assets/images/rights/line.png");
          background-size: 100% 100%;
          background-repeat: no-repeat;
          position: absolute;
          right: 20px;
          bottom: 123px;
        }
      }
      .tip {
        font-family: FZCuYuan;
        font-weight: 400;
        font-size: 22px;
        color: #d4bee7;
        margin-bottom: 58px;
      }
      .copyBtn {
        width: 268px;
        height: 104px;
        background: url("../../assets/images/rights/btnbg.png");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        font-family: FZCuQian;
        font-weight: 400;
        font-size: 30px;
        color: #38373d;
        font-style: italic;
        text-align: center;
        padding-top: 25px;
      }
    }
  }

  .addressPart {
    .addressBtn {
      width: 50%;
      padding: 20px;
      color: #fff;
      border: 1px solid #8983d5;
      text-align: center;
    }

    .tip {
      padding: 20px 60px;
      color: #fff;
    }

    .showInfo {
      width: calc(100% - 50px);
      position: relative;
      color: #fff;
      border: 1px solid #8983d5;
      padding: 20px;

      .updateBtn {
        position: absolute;
        right: 0;
        top: 0;
        background: #fff;
        padding: 0 20px;
        color: #000;
      }
    }

    .pop-mask {
      position: fixed;
      top: 0;
      left: 0;
      width: 750px;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.6);
      overflow: hidden;
      z-index: 999;
    }

    .container {
      position: absolute;
      width: 100%;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    .confirm-layer {
      position: relative;
      width: 100%;
      height: auto;
      background: url("../../assets/images/rights/MSP_Common_Panel_04@2x.png");
      background-size: 100% 100%;

      .layer-title {
        font-family: FZCuQian;
        font-weight: 400;
        font-size: 46px;
        color: #ffffff;
        text-rendering: 0.3px #8983d5;
        font-style: italic;
        -webkit-text-stroke: 0.3px #8983d5;
        position: absolute;
        top: 90px;
        left: 30px;
      }
      .layer-close-img {
        position: absolute;
        top: 12px;
        right: 26px;
        width: 51px;
        height: 51px;
        background: url("../../assets/images/rights/close.png");
        background-size: 100% 100%;
      }
      .layer-message {
        width: 100%;
        font-size: 32px;
        color: #8f8ad3;
        font-family: FZCuQian;

        .box,
        .textareaBox {
          width: 676px;
          height: 68px;
          margin: 0 auto;
          background: url("../../assets/images/rights/MSP_Lifestreet_Panel_Codebg01@2x.png");
          background-size: 100% 100%;
          padding: 0 60px;
          line-height: 60px;
          font-weight: 500;
          overflow: hidden;
          border: 0;
        }

        .title {
          line-height: 60px;
        }

        .textareaBox {
          height: 300px;
          textarea {
            width: 556px;
            height: 230px;
            border: 0;
            overflow-y: auto;
            background: transparent;
            resize: none;
          }
        }

        .desc {
          text-align: center;
          font-family: FZCuQian;
          color: #8f8ad3;
          font-size: 30px;
          margin-top: 34px;
          .desc_icon {
            width: 24px;
            height: 24px;
            margin-right: 8px;
            background: url("../../assets/images/rights/desc_icon@2x.png") 0 0
              no-repeat;
            background-size: 100% 100%;
          }
        }
      }
    }
    .layer-btns {
      display: flex;
      justify-content: space-between;
      margin: 53px 22px 0 172px;
      .btn {
        width: 286px;
        height: 104px;
        font-family: YouSheBiaoTiYuan;
        font-size: 36px;
        color: #20353a;
        line-height: 84px;
        text-align: center;
        font-style: normal;
      }
      .layer-cancel {
        background: url("../../assets/images/rights/MSP_Common_Btn_white_01@2x.png");
        background-size: 100% 100%;
      }
      .layer-confirm {
        background: url("../../assets/images/rights/MSP_Common_Btn_Green_02@2x.png");
        background-size: 100% 100%;
      }
    }
  }
}
</style>
